package com.gant.view;

import javafx.scene.control.TextArea;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import java.util.List;
import javafx.scene.control.TreeItem;

public class HighlightTreeCell extends TreeCell<String> {
    private final List<TreeItem<String>> matches;
    private final TextField textField;

    public HighlightTreeCell(List<TreeItem<String>> matches) {
        this.matches = matches;
        this.textField = createSelectableTextField();
        configureEventHandling();
    }

    private TextField createSelectableTextField() {
        TextField tf = new TextField();
        tf.setEditable(false); // 禁止编辑但允许选择
        tf.setStyle("-fx-background-color: transparent; -fx-border-color: transparent;");
        tf.getStyleClass().add("selectable-text");
        return tf;
    }

    private void configureEventHandling() {
        // 允许手动选择文本
        textField.addEventFilter(MouseEvent.MOUSE_PRESSED, event -> {
            // 允许默认的焦点和选择行为
        });

        // 阻止双击事件传递到TreeCell（避免展开/折叠）
        this.addEventFilter(MouseEvent.MOUSE_PRESSED, event -> {
            if (event.getClickCount() == 2) {
                event.consume();
            }
        });
    }
    @Override
    protected void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        if (empty || item == null) {
            setText(null);
            setGraphic(null);
        } else {
            textField.setText(item);
            setGraphic(textField);
            updateHighlightStyle();
        }
    }

    private void updateHighlightStyle() {
        textField.getStyleClass().removeAll("highlighted");
        if (matches.contains(getTreeItem())) {
            textField.getStyleClass().add("highlighted");
        }
    }

    @Override
    public void startEdit() { /* 禁用编辑 */ }

    @Override
    public void cancelEdit() { /* 禁用取消编辑 */ }
}